package com.bawei.es.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.es.service.EsDocService;
import com.bawei.es.service.EsIndexService;
import com.bawei.system.domain.vo.EsDocInsertVo;
import com.bawei.system.domain.vo.EsDocQueryVo;
import com.bawei.system.domain.vo.PageVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.common.text.Text;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsDocServiceImpl implements EsDocService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private EsIndexService esIndexService;

    @Override
    public R<Boolean> batchInsertDocs(List<EsDocInsertVo> esDocInsertVo) {
        BulkRequest request = new BulkRequest();
        esDocInsertVo.forEach(e -> {
            IndexRequest source = new IndexRequest(e.getIndexName()).source(e.getData(), XContentType.JSON);
            if (StringUtils.isNotEmpty(e.getId())) {
                source.id(e.getId());
            }
            request.add(source);
        });
        try {
            BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            return R.ok(true, "插入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail(false, "插入失败");
    }

    @Override
    public R<List<Map>> queryDocs(EsDocQueryVo searchReq) {
        if (StringUtils.isEmpty(searchReq.getKeyWord())) {
            throw new ServiceException("搜索参数不可以为空");
        }

        SearchRequest searchRequest = new SearchRequest(searchReq.getIndexName());
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 商品名称搜索
        List<String> fields = searchReq.getFirlds();
        String[] array = fields.toArray(new String[fields.size()]);
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(searchReq.getKeyWord(), array);
        boolQueryBuilder.must(multiMatchQueryBuilder);
        // 分页
        PageVo pageVo = searchReq.getPageVo();
        searchSourceBuilder.from((pageVo.getCurrentPage() - 1) * pageVo.getPageSize());
        searchSourceBuilder.size(pageVo.getPageSize());

        searchSourceBuilder.query(boolQueryBuilder);

        //调用高亮检索方法
        HighlightBuilder highlightBuilder = highlightSearch(searchReq);

        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchResponseHits = searchResponse.getHits();
            // 若未查询到数量结果，直接进行返回
            List<Map> productInfoResponseList = new ArrayList<>();
            SearchHit[] searchHits = searchResponseHits.getHits();
            for (SearchHit searchHit : searchHits) {
                // 源数据
                String sourceAsString = searchHit.getSourceAsString();
                Map productInfoMap =
                        JSONObject.parseObject(sourceAsString, Map.class);
                // 高亮
                Map<String, HighlightField> highlightFields =
                        searchHit.getHighlightFields();
                if (highlightFields != null) {
                    for (String field : fields) {
                        HighlightField highlightField = highlightFields.get(field);
                        if (highlightField != null) {
                            // 拼装
                            Text[] fragments = highlightField.getFragments();
                            StringBuilder sb = new StringBuilder();
                            for (Text fragment : fragments) {
                                sb.append(fragment);
                            }
                            productInfoMap.put(field, sb.toString());
                        }
                    }
                }
                productInfoResponseList.add(productInfoMap);
                return R.ok(productInfoResponseList);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 高亮检索
     * @param searchReq
     * @return
     */
    private HighlightBuilder highlightSearch(EsDocQueryVo searchReq) {
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        List<String> searchFields = searchReq.getFirlds();
        List<String> highLightFields = searchReq.getFirlds();
        if (CollectionUtils.isEmpty(highLightFields)){
            highLightFields = searchFields;
        }
        for (String field : highLightFields) {
            highlightBuilder.field(field);
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
        }
        return highlightBuilder;
    }

    @Override
    public void batchInsertDocs(String indexName, List<String> ids) {
            BulkRequest request = new BulkRequest();
            ids.forEach(id -> {
                DeleteRequest delete = new DeleteRequest(indexName).id(id);
                request.add(delete);
            });
        try {
            restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public R queryDocsSuggestions(String indexName, String keyWork, String suggestFiled) {
        // 参数校验
        R<Boolean> booleanR = esIndexService.indexExit(indexName);
        if (!booleanR.isSuccess()){
            throw new RuntimeException("索引不存在！");
        }

        // 自动补全
        SearchRequest request = new SearchRequest("product");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "title_suggest",
                SuggestBuilders
                        .completionSuggestion(suggestFiled)
                        //关键字
                        .prefix(keyWork)
                        //跳过数据
                        .skipDuplicates(true)
                        //显示10条
                        .size(10)
        ));
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Suggest suggest = response.getSuggest();
        List<String> list = new ArrayList<>();
        suggest.getSuggestion("title_suggest").forEach(suggestion -> {
            suggestion.getOptions().forEach(entry -> {
                list.add(entry.getText().string());
            });
        });
        return R.ok(list);
    }
}
